package com.thesis.manage.common.exception;

import com.alibaba.fastjson.JSONObject;
import com.thesis.manage.common.email.EmailSendUtil;
import com.thesis.manage.common.entity.ExceptionLog;
import com.thesis.manage.common.service.ExceptionLogService;
import com.thesis.manage.common.utils.IpUtil;
import com.thesis.manage.common.utils.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author php
 * @date 2017/12/13
 * 统一异常处理
 */
//@ControllerAdvice
public class GlobalExceptionHandle {

    private static final String SUBJECT = "异常日志";

    @Value("${spring.application.name}")
    private String applicationName;
    @Value("${error.accept.email}")
    private String errorAcceptEmail;
    @Resource
    private EmailSendUtil emailSender;

    @Resource
    private ExceptionLogService exceptionLogService;

    @ExceptionHandler({Exception.class})
    public Result exceptionHandle(Exception e) {
        //判断是否是自定义错误
        if (e instanceof CommonException) {
            CommonException exception = (CommonException) e;
            //返回状态码，错误消息,400代表执行失败
            return Result.build(400, exception.getValue(), null);
        }
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpServletResponse response = requestAttributes.getResponse();
        ExceptionLog exceptionLog = new ExceptionLog();
        exceptionLog.setIp(IpUtil.getIpAddr(request));
        exceptionLog.setServerName(applicationName);
        exceptionLog.setUrl(request.getRequestURL().toString());
        exceptionLog.setMethod(request.getMethod());
        exceptionLog.setMessage(e.getMessage());
        exceptionLog.setCode(response.getStatus());
        exceptionLogService.insert(exceptionLog);
        //发送邮件通知
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("你好，");
        stringBuilder.append(this.applicationName);
        stringBuilder.append("，你管理的系统");
        stringBuilder.append(this.applicationName);
        stringBuilder.append("发生了异常,具体内容如下:");
        stringBuilder.append(JSONObject.toJSONString(exceptionLog));
        stringBuilder.append("，请尽快解决！");
        this.emailSender.send(errorAcceptEmail, this.applicationName + SUBJECT, stringBuilder.toString());
        return Result.build(500, "未知错误", null);
    }

}
